<?php

/**
* 
*/
class Router
{

  private $controllers;
  private $defaultController;
  private $defaultAction;
  private $errorController;
  private $error404Action;

  /**
   * [__construct description]
   * @param $controller : controlleur génétal de l'application
   */
  function __construct($controllers, $default, $error)
  {
    $this->defaultController = $default['defaultController'];
    $this->controllers = $controllers;
    $this->defaultAction = $default['defaultAction'];
    $this->errorController = $error['errorController'];
    $this->error404Action = $error['error404Action'];
  }



  /** 
   * Récupération de la variable GET ou POST "action" GET (prioritaire)
   * Appel dynamique de la méthode du controller de type "ACTION_NAMEAction()"
   * exemple : Si le paramètre 'action' est 'list'
   * Cela va appeler la méthode listAction du controlleur. 
   */
  function start()
  {
    $currentController = null;
    if(isset($_GET['controller']) && $_GET['controller'] != "")
    {
        // On teste si le controller existe
        if(isset($this->controllers[$_GET['controller']]))
        {
          $currentController = $this->controllers[$_GET['controller']];
        } else
        {
          $currentController = $this->controllers[$this->defaultController];
        }
    } elseif (isset($_POST['controller']) && $_POST['controller'] != "")
    {
      // On teste si le controller existe
      if(isset($this->controllers[$_POST['controller']]))
      {
        $currentController = $this->controllers[$_POST['controller']];
      } else
      {
        $currentController = $this->controllers[$this->defaultController];
      }
    } else
    {
      // controlleur par défaut
      $currentController = $this->controllers[$this->defaultController];
    }

    if(isset($_GET['action']) && $_GET['action'] != "")
      $action = $_GET['action'];
    else if(isset($_POST['action']) && $_POST['action'] != "")
      $action = $_POST['action'];
    else
      $action = $this->defaultAction;

    $action .= "Action";

    // Appel dynamique
    if(method_exists($currentController, $action))
    {
      $currentController->{$action}();
    }  
    else
    {
      $action = "indexAction";
      $currentController->{$this}();
    }
  }
}

?>